package com.voxel.sense.infomsg;

import android.Manifest;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocationClient;
import com.example.com.common.app.BaseActivity;
import com.example.com.common.utils.L;
import com.example.com.common.utils.SizeUtils;
import com.example.com.common.utils.ToastUtil;
import com.voxel.sense.infomsg.module.login.LoginActivity;
import com.voxel.sense.infomsg.module.permission.PermissionsActivity;
import com.voxel.sense.infomsg.utils.CheckPermission;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.share.SPEngine;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class LaunchActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {
    // Drawable
//    @BindView(R.id.view_page)
//    ViewPager view_page;
    @BindView(R.id.bt_skip)
    Button bt_skip;
    @BindView(R.id.ll_dot)
    LinearLayout ll_dot;
    private ArrayList<ImageView> mDotViews;
    //    private LauncherPageApdater mPageApdater;
    private Handler mHandler = new Handler();
    private boolean isFirst = true;
    @BindView(R.id.go_home)
    TextView goHome;

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_launch;
    }

    @Override
    protected void initWidows() {
        super.initWidows();
    }

    @Override
    protected void initData() {

        AMapLocationClient.updatePrivacyShow(this, true, true);
        AMapLocationClient.updatePrivacyAgree(this, true);
        super.initData();
        requestPerm();
        initSpanlshPage();
        initDots();
    }

    private void initSpanlshPage() {
        SPEngine.getSPEngine().setEnterGuide(true);
        final int[] imageId = {R.mipmap.logo, R.mipmap.bg_launch2};
//        mPageApdater = new LauncherPageApdater(this, imageId);
//        view_page.setAdapter(new LauncherPageApdater(this, imageId));
//        view_page.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
//            @Override
//            public void onPageSelected(int position) {
//                super.onPageSelected(position);
//                for (int i = 0; i < mDotViews.size(); i++) {
//                    if (i == position) {
//                        mDotViews.get(i).setEnabled(true);
//                        mDotViews.get(i).requestLayout();
//                    } else {
//                        mDotViews.get(i).setEnabled(false);
//                        mDotViews.get(i).requestLayout();
//                    }
//                }
//            }
//        });

        //定时翻页
//        mHandler = new Handler() {
//            @Override
//            public void handleMessage(Message msg) {
//                super.handleMessage(msg);
//                int currentItem = view_page.getCurrentItem() + 1;
//                if (currentItem < imageId.length) {
//                    view_page.setCurrentItem(currentItem);
//                    mHandler.sendEmptyMessageDelayed(1, 2000);
//                } else {
//                    reallySkip();
//                }
//            }
//        };
//        mHandler.sendEmptyMessageDelayed(1, 3000);

    }

    @Override
    protected void onResume() {
        super.onResume();
        // 权限检测，跳转
    }

    @OnClick({R.id.bt_skip, R.id.go_home})
    void OnclickEvent(View view) {
        reallySkip();
    }


    /**
     * 真实的跳转
     */
    private void reallySkip() {
        mHandler.removeCallbacksAndMessages(null);
//         权限检测，跳转
        if (CheckPermission.haveAll(this)) {
            // 检查跳转到主页还是登录
            //TODO:已登录状态，直接跳转界面
            if (SPEngine.getSPEngine().isLoginState()&&!TextUtils.isEmpty(SPEngine.getSPEngine().getUserInfo().getSetMobileToken())) {
                MainActivity.show(this);
            } else {
                LoginActivity.show(LaunchActivity.this);
            }
            finish();
        } else {
            L.d("----没权限:");
            requestPerm();
//            PermissionsActivity.show(this);
        }

    }


    private void initDots() {
//        mDotViews = new ArrayList<>();
//        int margin = SizeUtils.dp2px(10);
//        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//        params.setMargins(margin, margin, margin, margin);
//        L.d("view_page.getChildCount():" + view_page.getChildCount());
//        for (int i = 0; i < mPageApdater.getCount(); i++) {
//            ImageView iv = new ImageView(this);
//            iv.setLayoutParams(params);
//            iv.setImageResource(R.drawable.select_page_dot);
//            if (i == 0) {
//                iv.setEnabled(true);
//            } else {
//                iv.setEnabled(false);
//            }
//            mDotViews.add(iv);
//            ll_dot.addView(iv);
//        }
//        L.d("mDotViews:" + mDotViews.size());
    }

    // 权限回调的标示
    private static final int RC = 0x0100;
    @AfterPermissionGranted(RC)
    private void requestPerm() {
        String[] perms = new String[]{
          android.Manifest.permission.INTERNET,//检查的网络权限
          android.Manifest.permission.ACCESS_NETWORK_STATE,
          android.Manifest.permission.ACCESS_WIFI_STATE,
          android.Manifest.permission.READ_EXTERNAL_STORAGE,// 读取权限
          android.Manifest.permission.WRITE_EXTERNAL_STORAGE,//// 写入权限
          android.Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,//允许程序访问CellID或WiFi热点来获取粗略的位置
          android.Manifest.permission.ACCESS_COARSE_LOCATION,//用于申请调用A-GPS模块
          android.Manifest.permission.ACCESS_FINE_LOCATION,//用于访问GPS定位
          android.Manifest.permission.CAMERA,//摄像头
          Manifest.permission.RECORD_AUDIO,//录音
        };
        if (CheckPermission.haveAll(Factory.app())) {
//            ToastUtil.showToastShort(Factory.app(), R.string.label_permission_ok);
            // Fragment 中调用getView得到跟布局，前提是在onCreateView方法之后
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (SPEngine.getSPEngine().isLoginState()&&!TextUtils.isEmpty(SPEngine.getSPEngine().getUserInfo().getSetMobileToken())) {
                        MainActivity.show(LaunchActivity.this);
                    } else {
                        LoginActivity.show(LaunchActivity.this);
                    }
                    finish();
                }
            }, 1000);
//            LoginActivity.show(this);

        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.title_assist_permissions),
              RC, perms);
        }
    }
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        ToastUtil.showToastShort(Factory.app(), "请先开启app权限");

        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog
              .Builder(this)
              .setTitle("权限设置")
              .setRationale("您拒绝了授予程序权限，有部分必须权限未开启，是否要到程序设置里开启权限")
              .setNegativeButton("取消退出")
              .build()
              .show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
}
